package me.flyray.merchant.serverDemo.okHttpUtil;

import android.text.TextUtils;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/9/19 0019.
 */

public class OKHttpUtil  {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private String responses = "";
    private static OKHttpUtil okHttpUtil = null;
    private String ssion = "";

    public static OKHttpUtil getInstance() {
        if (null == okHttpUtil) {
            okHttpUtil = new OKHttpUtil();
        }
        return okHttpUtil;
    }


    /**
     * @param url
     * @param json
     * @return
     * @throws IOException
     */
    public String postDataString(String url, String json) throws IOException {
           Log.i("发送出去的参数:", json);
//        OkHttpClient mOkHttp = new OkHttpClient.Builder().connectTimeout(15000, TimeUnit.SECONDS).build();

        OkHttpClient mOkHttp = new OkHttpClient().newBuilder().hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        }).build();
        RequestBody body = RequestBody.create(JSON, json);
        Request request;


        if (!TextUtils.isEmpty(ssion)) {
            request = new Request.Builder().url(url).post(body).addHeader("Cookie", ssion).build();
            ssion = "";
        } else {
            request = new Request.Builder().url(url).post(body).build();
        }

        Log.i("Request", request.toString());
        Response response = mOkHttp.newCall(request).execute();


        String str = response.body().string();
        Log.i("请求到的数据:", str);
        String[] strs = new String[0];
        try {
            JSONObject jsonObject = new JSONObject(str);
            if ("N".equals(jsonObject.getString("resultType"))) {
                Headers headers = response.headers();
                List<String> cookies = headers.values("Set-Cookie");
                String ss = "";
                for (String s : cookies) {
                    ss += s;
                }
                strs = ss.split(",");
                ssion = strs[0];
                Log.i("ssion:", ssion);
            }
        } catch (JSONException e) {
            ssion = null;
        }
        return str;
    }


}
